import { Button } from 'antd';
import React, { useMemo, useState } from 'react';

const UseMemo = () => {
    let [upNum, setUpNum] = useState(0);
    let [downNum, setDownNum] = useState(0);
    let [number, setNumber] = useState(100);
    // 每次渲染都会重新计算,没有第二个参数每次渲染都会重新计算，有了只有当依赖项改变才会重新计算
    const sumNum = useMemo(() => {
        return upNum + downNum;
    }, [upNum, downNum])
    const approvalRating = useMemo(() => {
        let value = upNum / sumNum * 100;
        return Object.is(NaN, value) ? '-' : value.toFixed(2)
    }, [upNum, sumNum])
    return (
        <div>
            <p>支持:{upNum}</p>
            <p>反对:{downNum}</p>
            <Button type="primary" onClick={() => setUpNum(upNum + 1)}>支持</Button>
            <Button type="primary" danger onClick={() => setDownNum(downNum + 1)}>反对</Button>
            <p>投票人数：{sumNum}</p>
            {approvalRating && <p>支持比例：{approvalRating}%</p>}
            <p>无关的数:{number}   <Button onClick={() => setNumber(number + 100)}>+100</Button></p>
        </div>
    );
}

export default UseMemo;
